package com.haitaoit.chengquan.ui.invitation.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.telephony.TelephonyManager;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.IBaseActivity;
import com.haitaoit.chengquan.base.MyCallBack;
import com.haitaoit.chengquan.business.http.bean.ParamObj;
import com.haitaoit.chengquan.module.home.adapter.forum.QImageAdapter;
import com.haitaoit.chengquan.ui.equipment.response.ResponseItem;
import com.haitaoit.chengquan.ui.invitation.adapter.PhotoAdapter;
import com.haitaoit.chengquan.ui.invitation.bean.ImageBean;
import com.haitaoit.chengquan.ui.invitation.request.ApiRequest;
import com.haitaoit.chengquan.ui.invitation.request.bean.InvitationCommitBean;
import com.haitaoit.chengquan.ui.invitation.response.InvitationBean;
import com.haitaoit.chengquan.ui.invitation.response.InvitationTypeBean;
import com.haitaoit.chengquan.utils.BitmapUtils;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.ImageUtils;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.StringUtils;
import com.haitaoit.chengquan.utils.TakeImage;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.MyGridView;
import com.haitaoit.chengquan.view.pickerview.OptionsPopupWindow;
import com.lidroid.xutils.view.annotation.ViewInject;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Created by Administrator on 2017/5/8.
 */

public class EditInvitationActivity extends IBaseActivity  {
//    private TextView forum_type;
    private EditText add_forum_title;
    private EditText add_forum_content;
    private MyGridView myGridView;
    private TextView tv_update;
    @ViewInject(R.id.tv_invitation_type)
    TextView tv_invitation_type;
    private QImageAdapter adapter;
    private List<InvitationTypeBean.ResponseBean> titleModels;
    private String type_id;
    private int curImg_index;
    private Handler handler=new Handler(Looper.getMainLooper());;
    private TakeImage takeImage;
    private String invitationId;
    private PhotoAdapter photoAdapter;
    ImageView iv_image;
    private int tieziId;
    @Override
    protected int setContentView() {
        return R.layout.activity_edit_invitation;
    }

    @Override
    protected String setTitle() {
        return "编辑帖子";
    }

    @Override
    public void initView() {
        invitationId=getIntent().getStringExtra("id");
        add_forum_title = (EditText) findViewById(R.id.add_forum_title);
        add_forum_content = (EditText) findViewById(R.id.add_forum_content);
        iv_image = (ImageView) findViewById(R.id.iv_image);
        myGridView = (MyGridView) findViewById(R.id.myGridView);
        tv_update = (TextView) findViewById(R.id.tv_update);
        tv_update.setText("修 改");
        tv_update.setOnClickListener(this);
        tv_invitation_type.setOnClickListener(this);
        photoAdapter=new PhotoAdapter(this,R.layout.item_select_photo);
    }

    @Override
    public void initData() {
//        new PublicPostTypeHttp(this, handler, GetNotParam(), 1);//
        int i = (int) Math.floor(Math.random() * 9000 + 1000);
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("rnd", i + ""));
        String sign = GetSign.genPackageSign(list);
        ApiRequest.getInvitationType(i+"", sign, new MyCallBack<InvitationTypeBean>(this) {
            @Override
            public void onSuccessful(InvitationTypeBean response) {
                if(response.getErrCode()==0){
                    titleModels=response.getResponse();
                    getInvitationData();
                }
            }
        });

    }
    //上传图片实体
    InvitationCommitBean.ImgListBean imgBean;
    //上传图片list
    List<InvitationCommitBean.ImgListBean> beanList=new ArrayList<>();
    //提交帖子实体
    InvitationCommitBean commitBean;
    @Override
    protected void viewOnClick(View v) {
        switch (v.getId()){
            case R.id.tv_invitation_type:
                /*new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String url="http://cq.hai-tao.net/upload/201705/22/1705221859226583.jpg";
                        int urlIndex=StringUtils.getFromIndex(url,"/",3);
                        final InputStream img = ApiRequest.getImg(url.substring(0, urlIndex + 1), url.substring(urlIndex + 1));
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                iv_image.setImageBitmap(BitmapFactory.decodeStream(img));
                            }
                        });
                    }
                }).start();*/
                updateBigtype(titleModels);
                break;
            case R.id.tv_update:
                showLoading();
                commitBean=new InvitationCommitBean();
                commitBean.setEsther_class_id(Integer.parseInt(type_id));
                commitBean.setTitle(getSStr(add_forum_title));
                commitBean.setContent(getSStr(add_forum_content));
                final List<ImageBean> data = photoAdapter.getData();

                if(data!=null&&data.size()>0){
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            for (int i = 0; i < data.size(); i++) {
                                if(data.get(i).getType()==0){//0网络图片，1本地图片,.replace(ExitApplication.baseUrl,"")
                                    String beforUrl=data.get(i).getImgPath();
                                    int urlIndex= StringUtils.getFromIndex(beforUrl,"/",3);
                                    InputStream is = ApiRequest.getImg(beforUrl.substring(0,urlIndex+1),beforUrl.substring(urlIndex+1));
                                    if(is==null){
                                        getImgError("图片转换失败,请删除之后重试");
                                        return;
                                    }else{
                                        Bitmap bitmap = BitmapFactory.decodeStream(is);
                                        imgBean=new InvitationCommitBean.ImgListBean();
                                        imgBean.setImg_url(BitmapUtils.bitmapToStr(bitmap));
                                        beanList.add(imgBean);
                                    }
                                }else{
                                    FileInputStream fis = null;
                                    try {
                                        String path=ImageUtils.filePath;
                                        String name=ImageUtils.fileName;
                                        String smallBitmap = ImageUtils.getSmallBitmap(data.get(i).getImgPath(), path, name);
                                        fis = new FileInputStream(smallBitmap);
                                        Bitmap bitmap  = BitmapFactory.decodeStream(fis);
                                        imgBean=new InvitationCommitBean.ImgListBean();
                                        imgBean.setImg_url(BitmapUtils.bitmapToStr(bitmap));
                                        beanList.add(imgBean);
                                    } catch (FileNotFoundException e) {
                                        getImgError("获取手机图片失败");
                                        e.printStackTrace();
                                        return;
                                    }

                                }
                            }
                            getImgResult(commitBean,beanList);
                        }


                    }).start();
                }else{
                    commitBean.setImg_list(beanList);
                    commitData(commitBean);
                }

//                iv_image.setImageBitmap(bitmap);
                /*ApiRequest.getImg2(new MyCallBack<ResponseBody>(this) {
                    @Override
                    public void onSuccessful(ResponseBody response) {
                        InputStream is = null;
                        try {
                            is = response.byteStream();
                            Bitmap bitmap = BitmapFactory.decodeStream(is);
                            iv_image.setImageBitmap(bitmap);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        *//*byte[] bytes = new byte[0];
                        try {
                            bytes = response.bytes();
                            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                            iv_image.setImageBitmap(bitmap);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }*//*

                    }
                });*/

            break;

        }
    }
    private void getImgResult(InvitationCommitBean bean,List<InvitationCommitBean.ImgListBean> beanList) {
        bean.setImg_list(beanList);
        commitData(bean);
    }
    private void getImgError(final String msg) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                dismissLoading();
                ToastUtils.showToast(msg);
            }
        });
    }

    private void commitData(InvitationCommitBean bean) {
        List<ParamObj> paramObjs =new ArrayList<ParamObj>();
        paramObjs.add(new ParamObj("user_id", PreferenceUtils.getPrefString("user_id", "")));
        paramObjs.add(new ParamObj("id",tieziId+""));
        String sign=GetHaveParam(paramObjs);
        ApiRequest.commitTieZi(tieziId+"", PreferenceUtils.getPrefString("user_id", ""), sign, bean, new MyCallBack<ResponseItem>(this) {
            @Override
            public void onSuccessful(ResponseItem response) {
                ToastUtils.showToast(response.getErrMsg());
                if(response.getErrCode()==0){
                    finish();
                }
            }
        });
    }

    private void getInvitationData() {
        //获取手机唯一标识
        TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        String equipment = TelephonyMgr.getDeviceId();
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("id",invitationId));
        String sign = GetSign.genPackageSign(list);

        Map<String,String> map=new HashMap<String,String>();
        map.put("id",invitationId);
        map.put("sign",sign);
        ApiRequest.getInvitationData(map, new MyCallBack<InvitationBean>(this) {
            @Override
            public void onSuccessful(InvitationBean response) {
                if(response.getErrCode()==0){
                    String title=response.getResponse().getTitle();
                    int type=response.getResponse().getClass_id();
                    type_id=type+"";
                    String content=response.getResponse().getContent();
                    tieziId = response.getResponse().getId();
                    List<InvitationBean.ResponseBean.ImgListBean> img_list = response.getResponse().getImg_list();
                    add_forum_title.setText(title);
                    add_forum_content.setText(content);
                    for (int i = 0; i < titleModels.size(); i++) {
                        if (titleModels.get(i).getId() == type) {
                            tv_invitation_type.setText(titleModels.get(i).getName());
                            break;
                        }
                    }
                    ImageBean bean;
                    List<ImageBean>imgList=new ArrayList<ImageBean>();
                    for (int i = 0; i < img_list.size(); i++) {
                        bean=new ImageBean();
                        bean.setType(0);
                        bean.setImgPath(img_list.get(i).getImg_url());
                        imgList.add(bean);
                    }
                    photoAdapter.setData(imgList);
                    myGridView.setAdapter(photoAdapter);
                    /*for (int i = 0; i < img_list.size(); i++) {
                        new ImgObj(0, 0, null, null);
                    }
                    adapter.getDataList().add(null);
                    myGridView.setAdapter(adapter);*/
                }else{
                }
            }
        });
    }



    private void updateBigtype(final List<InvitationTypeBean.ResponseBean> list) {
        final ArrayList<String> list2 = new ArrayList<String>();
        for (int i = 0; i < list.size(); i++) {
            list2.add(list.get(i).getName());
        }

        OptionsPopupWindow popSex = new OptionsPopupWindow(this, "");
        popSex.setPicker(list2);
        popSex.setSelectOptions(0);
        popSex.setOnoptionsSelectListener(new OptionsPopupWindow.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                tv_invitation_type.setText(list2.get(options1));
                type_id = list.get(options1).getId()+"";
            }
        });
        popSex.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);// popupwindow消失的时候恢复成原来的透明度
            }
        });
        popSex.showAtLocation(tv_invitation_type, Gravity.BOTTOM, 0, 0);
        backgroundAlpha(0.6f);
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;// 0.0-1.0
        getWindow().setAttributes(lp);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        takeImage.onActivityResult(requestCode, resultCode, data);
        if(requestCode==PhotoAdapter.selectPhoto&&resultCode==PhotoAdapter.selectPhotoResult){
            List<String> path = data.getStringArrayListExtra("path");
            ImageBean bean;
            List<ImageBean>imgList=new ArrayList<ImageBean>();
            for (int i = 0; i < path.size(); i++) {
                bean=new ImageBean();
                bean.setType(1);
                bean.setImgPath(path.get(i));//判断压缩
                imgList.add(bean);
            }
            photoAdapter.addData(imgList);
        }else if(PhotoAdapter.TAKE_PICTURE==requestCode &&resultCode == RESULT_OK){
            Luban.get(this)
                    .load(new File(ImageUtils.fileSavePath+ImageUtils.fileName))                     //传人要压缩的图片
                    .putGear(3)      //设定压缩档次，默认三挡
                    .setCompressListener(new OnCompressListener() { //设置回调
                        @Override
                        public void onStart() {
                            showLoading();
                        }
                        @Override
                        public void onSuccess(File file) {
                            String path=ImageUtils.filePath;
                            String name=ImageUtils.fileName;
                            ImageUtils.makeFolder(path,true);
                            ImageUtils.saveFile(file,path,name);
                            List<ImageBean>imgList=new ArrayList<ImageBean>();
                            ImageBean   bean=new ImageBean();
                            bean.setType(1);
                            bean.setImgPath(path+name);
                            imgList.add(bean);
                            photoAdapter.addData(imgList);
                            dismissLoading();
                        }
                        @Override
                        public void onError(Throwable e) {
                            dismissLoading();
                        }
                    }).launch();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler=null;
    }
}
